﻿#include "ThreadPool.h"
#include <assert.h>
#include <stdlib.h>
//初始化线程
struct ThreadPool* threadPoolInit(struct EventLoop* mainLoop, int count)
{
	struct ThreadPool* pool = (struct ThreadPool*)malloc(sizeof(struct ThreadPool));//申请堆内存
	pool->index = 0;//线程数组数组下标
	pool->isStart = false;
	pool->mainLoop = mainLoop;//主线程的反应堆模型
	pool->threadNum = count;//子线程个数
	pool->workerThreads = (struct WorkerThread*)malloc(sizeof(struct WorkerThread) * count);//存储子线程实例的数组
	return pool;
}
//启动线程
void threadPoolRun(struct ThreadPool* pool)
{
	assert(pool && !pool->isStart);//线程池 存在 且 未运行
	if (pool->mainLoop->threadID != pthread_self())//确保由主线程来启动
	{
		exit(0);
	}
	pool->isStart = true;//标记线程池启动
	if (pool->threadNum)//线程池内有线程
	{
		for (int i = 0; i < pool->threadNum; ++i)
		{
			workerThreadInit(&pool->workerThreads[i], i);//初始化工作线程的相关参数
			workerThreadRun(&pool->workerThreads[i]);//启动线程
		}
	}
}
//取出线程的eventloop
struct EventLoop* takeWorkerEventLoop(struct ThreadPool* pool)
{
	assert(pool->isStart);//线程池正在工作
	if (pool->mainLoop->threadID != pthread_self())//确保主线程操作
	{
		exit(0);
	}
	// 从线程池中找一个子线程, 然后取出里边的反应堆实例
	struct EventLoop* evLoop = pool->mainLoop;//获取主线程的mainloop，一开始线程池刚启动，建立连接用
	if (pool->threadNum > 0)//线程池已经初始化，且线程池内由线程
	{
		evLoop = pool->workerThreads[pool->index].evLoop;//获得子线程evloop
		pool->index = ++pool->index % pool->threadNum;//获得 “更新的” 子线程的编号，雨露均沾（都有活干）
	}
	return evLoop;
}